package com.liull.netty.itcast.nio.net.block;

import cn.hutool.core.lang.Console;
import com.liull.netty.itcast.nio.bytebuffer.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 21:41 2021/7/22
 * @Modified By:
 */
public class Server {
    public static void main(String[] args) {
        // 使用NIO来理解阻塞模式
        // 1.创建了服务器
        try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
            // 2。绑定监听端口
            ssc.bind(new InetSocketAddress(4567));
            // 3.连接集合
            List<SocketChannel> channels = new ArrayList<>();
            ByteBuffer buffer = ByteBuffer.allocate(16);
            while (true) {
                Console.log("connecting...");
                // 阻塞方法 等待客户端连接
                final SocketChannel channel = ssc.accept();
                Console.log("connected...channel:{}", channel);
                channels.add(channel);
                for (SocketChannel ch : channels) {
                    Console.log("before read ... {}", channel);
                    // 阻塞方法 等待客户端发送数据
                    ch.read(buffer);
                    buffer.flip();
                    ByteBufferUtil.printDesc(buffer);
                    buffer.clear();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
